package com.fsd.experiment3;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ProgressBarActivity extends AppCompatActivity {

    private int [] data = new int[100];
    int hasData = 0;
    int status = 0;
    ProgressBar bar;
    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0x111)
            {
                bar.setProgress(status);
            }
            else{
                Toast.makeText(ProgressBarActivity.this, "任务执行成功", Toast.LENGTH_SHORT).show();
                hasData = 0;
                status = 0;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_bar);


        Button btnTask = findViewById(R.id.btn_task1);
        bar = findViewById(R.id.bar);
        btnTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread()
                {
                    @Override
                    public void run() {
                        super.run();
                        while (status<100)
                        {
                            status = dowork();
                            handler.sendEmptyMessage(0x111);
                        }
                        handler.sendEmptyMessage(0x110);
                    }
                }.start();
            }
        });

    }
    public int dowork(){
        data[hasData++] = (int) (Math.random()*100);
        try
        {
            Thread.sleep(100);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        return hasData;
    }
}
